import React from "react";
import { Form, Input, Button } from "antd";
import { useAuth } from "context/auth-context";
import styled from "@emotion/styled";
import { useAsync } from "utils/index";

const LoginScreen = ({ onError }: { onError: (error: Error) => void }) => {
  const { login, user } = useAuth();
  const { run, isLoading } = useAsync(undefined, { thorwOnError: true });
  const handleSubmit = async (values: {
    username: string;
    password: string;
  }) => {
    try {
      await run(login(values));
    } catch (error: any) {
      onError(error);
    }
  };
  return (
    <Form onFinish={handleSubmit}>
      <Form.Item
        name={"username"}
        rules={[{ required: true, message: "请输入用户名" }]}
      >
        <div>
          {" "}
          <label htmlFor="username">用户名</label>
          <Input placeholder="用户名" type={"text"} id={"username"}></Input>
        </div>
      </Form.Item>
      <Form.Item
        name={"password"}
        rules={[{ required: true, message: "请输入密码" }]}
      >
        <div>
          {" "}
          <label htmlFor="password">密码</label>
          <Input placeholder="密码" type={"password"} id={"password"}></Input>
        </div>
      </Form.Item>
      <Form.Item>
        <LoginButton loading={isLoading} htmlType="submit" type={"primary"}>
          登录
        </LoginButton>
      </Form.Item>
    </Form>
  );
};
export const LoginButton = styled(Button)`
  width: 100%;
`;
export default LoginScreen;
